package com.yuexunit.mobilenurse.module.BloodManage.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.base.titlebar.TitleBar_DocAdvice;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.BloodManage.adapter.ApplyAdapter;
import com.yuexunit.mobilenurse.module.BloodManage.bean.BloodDataBean;
import com.yuexunit.mobilenurse.module.BloodManage.bean.SingleBloodBag;
import com.yuexunit.mobilenurse.module.BloodManage.model.impl.BloodApplyModel;
import com.yuexunit.mobilenurse.module.BloodManage.presenter.IBloodApplyPresenter;
import com.yuexunit.mobilenurse.module.BloodManage.presenter.impl.BloodApplyPresenter;
import com.yuexunit.mobilenurse.module.BloodManage.ui.view.IBloodApplyView;
import com.yuexunit.mobilenurse.scan.Idata.ScannerInerface;
import com.yuexunit.mobilenurse.util.CreateJson;
import com.yuexunit.mobilenurse.widget.EmptyLayout;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.kymjs.kjframe.utils.SystemTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2018/7/11 0011.
 */

public class Act_Blood_Apply_Idata extends TitleBar_DocAdvice implements IBloodApplyView {
    @Bind(R.id.titlebar_docadvice_tv_title)
    public TextView titlebar_docadvice_tv_title;
    @Bind(R.id.docactvice_name)
    public TextView docactvice_name;
    @Bind(R.id.docactvice_bedno)
    public TextView docactvice_bedno;
    @Bind(R.id.docactvice_visitno)
    public TextView docactvice_visitno;
    @Bind(R.id.act_testdetail_list)
    public ListView act_testdetail_list;
    @Bind(R.id.empty_layout)
    public EmptyLayout mEmptyLayout;

    public static final int DOWNLOAD_NETERROR = -1;

    //记录Log
    private final Logger log = LoggerFactory.getLogger(Act_Blood_Apply_Joyree.class);

    BaseAdapter adapter;

    IBloodApplyPresenter presenter;

    ScannerInerface scanner;
    IntentFilter intentFilter;
    BroadcastReceiver scanReceiver;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_blood_apply);
        ButterKnife.bind(this);
        presenter = new BloodApplyPresenter(new BloodApplyModel(),this);
    }

    @Override
    public void initData() {
        super.initData();
        mEmptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        initScanner();
        if(SystemTool.checkNet(aty)) {
            Map<String, String> params = new HashMap<>();
//            params.put("visitNo","492746");
            params.put("visitNo", PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO));
            params.put("pageIndex","1");
            params.put("pageSize","9999");
            presenter.getBloodDataList(params);
        }
        else
        {
            ViewInject.toast("网络异常，请检查网络是否连接!");
            log.error(CreateJson.LOG_JSON("", "1", PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_DEPTNO), ""));
        }
    }

    @Override
    public void setTitle()
    {
        titlebar_docadvice_tv_title.setText("申请列表");
        docactvice_name.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME));
        docactvice_bedno.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_BEDCODE));
        docactvice_visitno.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO));
    }

    @Override
    public  void onBackClick()
    {
        finish();
    }




    @Override
    public void showBloodDataList(BloodDataBean bloodDataBean) {
        adapter = new ApplyAdapter(act_testdetail_list,bloodDataBean.getDatas(),R.layout.item_apply);
        act_testdetail_list.setAdapter(adapter);
        mEmptyLayout.dismiss();
    }

    @Override
    public void PullDownRefreshState(int state) {
        switch (state) {
            case DOWNLOAD_NETERROR:
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                break;
        }
    }

    @Override
    public void getBloodBagData(SingleBloodBag singleBloodBag) {
        if(singleBloodBag.getStatus().equals("200"))
        {
            Bundle bundle = new Bundle();
            bundle.putString("requireNo",singleBloodBag.getDatas().get(0).getRequireNo());
            bundle.putSerializable("bloodbag",singleBloodBag.getDatas().get(0));
            Intent intent = new Intent(aty,Act_Blood_BloodDetail.class);
            intent.putExtras(bundle);
            startActivity(intent);
        }
        else {
            ViewInject.toast(singleBloodBag.getMessage());
        }
    }

    @Override
    public void onStop(){
        super.onStop();
        finishScanner();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        finishScanner();
    }

    private void initScanner(){
        scanner = new ScannerInerface(this);
        scanner.open();	//打开扫描头上电   scanner.close();//打开扫描头下电
        scanner.enablePlayBeep(true);//是否允许蜂鸣反馈
        scanner.enableFailurePlayBeep(true);//扫描失败蜂鸣反馈
        scanner.enablePlayVibrate(true);//是否允许震动反馈
        scanner.setCharSetMode(4);//设置解码方式
        //		scanner.enablShowAPPIcon(false);//是否允许显示iscan的应用程序图标   部分设备 调用出现异常，建议不要调用该功能
        //		scanner.enablShowNoticeIcon(false);//是否允许显示iscan通知栏图标     部分设备 调用出现异常，建议不要调用该功能
        scanner.enableAddKeyValue(1);/**附加无、回车、Teble、换行*/
        scanner.timeOutSet(2);//设置扫描延时2秒
        scanner.intervalSet(10); //设置连续扫描间隔时间
        scanner.lightSet(false);//关闭右上角扫描指示灯
        scanner.enablePower(true);//省电模式
        //		scanner.addPrefix("AAA");//添加前缀
        //		scanner.addSuffix("BBB");//添加后缀
        //		scanner.interceptTrimleft(2); //截取条码左边字符
        //		scanner.interceptTrimright(3);//截取条码右边字符
        //		scanner.filterCharacter("R");//过滤特定字符
        //		scanner.SetErrorBroadCast(true);//扫描错误换行
        //      scanner.resultScan();//恢复iScan默认设置

        scanner.lockScanKey();
        //锁定设备的扫描按键,通过iScan定义扫描键扫描，用户也可以自定义按键。
//		scanner.unlockScanKey();
        //释放扫描按键的锁定，释放后iScan无法控制扫描按键，用户可自定义按键扫描。

        /**设置扫描结果的输出模式，参数为0和1：
         * 0为模拟输出（在光标停留的地方输出扫描结果）；
         * 1为广播输出（由应用程序编写广播接收者来获得扫描结果，并在指定的控件上显示扫描结果）
         * 这里采用接收扫描结果广播并在TextView中显示*/
        scanner.setOutputMode(1);

        //扫描结果的意图过滤器的动作一定要使用"android.intent.action.SCANRESULT"
        intentFilter = new IntentFilter(AppConfig.IDATA);
        //注册广播接受者
        scanReceiver = new ScannerResultReceiver();
        registerReceiver(scanReceiver, intentFilter);
    }

    /**
     * 结束扫描
     */
    private void finishScanner(){
        scanner.scan_stop();
        //    	 scanner.close();	//关闭iscan  非正常关闭会造成iScan异常退出
        try {
            unregisterReceiver(scanReceiver);	//反注册广播接收者
        } catch (IllegalArgumentException e) {

        }
        scanner.continceScan(false);
    }

    /**
     * 扫描结果的广播接收者
     */
    private class ScannerResultReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(AppConfig.IDATA)){
                //获取扫描结果
                final String value = intent.getStringExtra("value");
                if(!value.equals(""))
                {
                    String code = "15"+value;
                    if(code.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_YX_RULE)))
//                    if(code.length()==10)
                    {
                        Map<String, String> params = new HashMap<>();
                        params.put("bagNo", code);
                        TelephonyManager telephonyManager = (TelephonyManager) aty
                                .getSystemService(Context.TELEPHONY_SERVICE);
                        params.put("setNo", telephonyManager.getDeviceId());
                        presenter.getBloodBagData(params);
                    }
                    else {
                        ViewInject.toast("此条码不是血袋号");
                    }
                }
            }
        }
    }
}
